<template>
  <div class="resource-status-manager">
    <!-- 三层状态卡片 -->
    <a-row :gutter="16" class="status-cards">
      <a-col :span="8">
        <a-card title="生命周期状态" size="small">
          <div class="status-content">
            <a-select
              v-model:value="resourceStatus.lifecycle"
              style="width: 100%"
              @change="updateLifecycleStatus"
              :loading="lifecycleLoading"
            >
              <a-select-option
                v-for="status in lifecycleStatuses"
                :key="status"
                :value="status"
              >
                <a-tag :color="getLifecycleStatusColor(status)">
                  {{ getLifecycleStatusLabel(status) }}
                </a-tag>
              </a-select-option>
            </a-select>
            <div class="status-info">
              <small
                >最后更新: {{ formatTime(resourceStatus.lastUpdated) }}</small
              >
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="可用性状态" size="small">
          <div class="status-content">
            <a-select
              v-model:value="resourceStatus.availability"
              style="width: 100%"
              @change="updateAvailabilityStatus"
              :loading="availabilityLoading"
            >
              <a-select-option
                v-for="status in availabilityStatuses"
                :key="status"
                :value="status"
              >
                <a-tag :color="getAvailabilityStatusColor(status)">
                  {{ getAvailabilityStatusLabel(status) }}
                </a-tag>
              </a-select-option>
            </a-select>
            <div class="status-info">
              <small
                >最后更新: {{ formatTime(resourceStatus.lastUpdated) }}</small
              >
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card title="版本状态" size="small">
          <div class="status-content">
            <a-select
              v-model:value="resourceStatus.version"
              style="width: 100%"
              @change="updateVersionStatus"
              :loading="versionLoading"
            >
              <a-select-option
                v-for="status in versionStatuses"
                :key="status"
                :value="status"
              >
                <a-tag :color="getVersionStatusColor(status)">
                  {{ getVersionStatusLabel(status) }}
                </a-tag>
              </a-select-option>
            </a-select>
            <div class="status-info">
              <small
                >最后更新: {{ formatTime(resourceStatus.lastUpdated) }}</small
              >
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 状态变更历史 -->
    <a-card title="状态变更历史" style="margin-top: 16px" size="small">
      <a-timeline>
        <a-timeline-item
          v-for="change in statusHistory"
          :key="change.id"
          :color="getStatusChangeColor(change.statusType)"
        >
          <template #dot>
            <a-tag :color="getStatusChangeColor(change.statusType)">
              {{ getStatusTypeLabel(change.statusType) }}
            </a-tag>
          </template>
          <div class="status-change-item">
            <div class="status-change-header">
              <span class="old-status">{{ change.oldStatus }}</span>
              <a-icon type="arrow-right" />
              <span class="new-status">{{ change.newStatus }}</span>
            </div>
            <div class="status-change-details">
              <p class="reason">{{ change.reason }}</p>
              <p class="meta">
                {{ formatTime(change.timestamp) }} - {{ change.operator }}
              </p>
            </div>
          </div>
        </a-timeline-item>
      </a-timeline>
    </a-card>

    <!-- 状态变更原因输入模态框 -->
    <a-modal
      v-model:open="reasonModalVisible"
      title="状态变更原因"
      @ok="confirmStatusChange"
      @cancel="cancelStatusChange"
    >
      <a-form layout="vertical">
        <a-form-item label="变更原因" required>
          <a-textarea
            v-model:value="statusChangeReason"
            :rows="3"
            placeholder="请输入状态变更原因"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import {
  ResourceLifecycleStatus,
  ResourceAvailabilityStatus,
  ResourceVersionStatus,
  type ResourceStatus,
  type StatusChangeHistory,
} from '#/api/resource-center/status-types';
import {
  updateResourceLifecycleStatus,
  updateResourceAvailabilityStatus,
  updateResourceVersionStatus,
  getResourceStatusHistory,
  getResourceStatus,
} from '#/api/resource-center/status-api';

interface Props {
  resourceId: string;
}

const props = defineProps<Props>();

// 响应式数据
const resourceStatus = reactive<ResourceStatus>({
  lifecycle: ResourceLifecycleStatus.DRAFT,
  availability: ResourceAvailabilityStatus.UNAVAILABLE,
  version: ResourceVersionStatus.DRAFT,
  lastUpdated: new Date(),
});

const statusHistory = ref<StatusChangeHistory[]>([]);
const lifecycleLoading = ref(false);
const availabilityLoading = ref(false);
const versionLoading = ref(false);
const reasonModalVisible = ref(false);
const statusChangeReason = ref('');
const pendingStatusChange = ref<{
  type: 'lifecycle' | 'availability' | 'version';
  status: string;
} | null>(null);

// 状态选项
const lifecycleStatuses = Object.values(ResourceLifecycleStatus);
const availabilityStatuses = Object.values(ResourceAvailabilityStatus);
const versionStatuses = Object.values(ResourceVersionStatus);

// 工具函数
const getLifecycleStatusColor = (status: ResourceLifecycleStatus) => {
  const colors = {
    [ResourceLifecycleStatus.DRAFT]: 'default',
    [ResourceLifecycleStatus.ACTIVE]: 'green',
    [ResourceLifecycleStatus.SUSPENDED]: 'orange',
    [ResourceLifecycleStatus.ARCHIVED]: 'red',
  };
  return colors[status] || 'default';
};

const getAvailabilityStatusColor = (status: ResourceAvailabilityStatus) => {
  const colors = {
    [ResourceAvailabilityStatus.AVAILABLE]: 'green',
    [ResourceAvailabilityStatus.RESERVED]: 'blue',
    [ResourceAvailabilityStatus.IN_USE]: 'orange',
    [ResourceAvailabilityStatus.UNAVAILABLE]: 'red',
    [ResourceAvailabilityStatus.FAILED]: 'red',
  };
  return colors[status] || 'default';
};

const getVersionStatusColor = (status: ResourceVersionStatus) => {
  const colors = {
    [ResourceVersionStatus.DRAFT]: 'default',
    [ResourceVersionStatus.STAGED]: 'blue',
    [ResourceVersionStatus.CANARY]: 'orange',
    [ResourceVersionStatus.ACTIVE]: 'green',
    [ResourceVersionStatus.DEPRECATED]: 'red',
    [ResourceVersionStatus.ROLLED_BACK]: 'red',
  };
  return colors[status] || 'default';
};

const getLifecycleStatusLabel = (status: ResourceLifecycleStatus) => {
  const labels = {
    [ResourceLifecycleStatus.DRAFT]: '草稿',
    [ResourceLifecycleStatus.ACTIVE]: '活跃',
    [ResourceLifecycleStatus.SUSPENDED]: '暂停',
    [ResourceLifecycleStatus.ARCHIVED]: '归档',
  };
  return labels[status] || status;
};

const getAvailabilityStatusLabel = (status: ResourceAvailabilityStatus) => {
  const labels = {
    [ResourceAvailabilityStatus.AVAILABLE]: '可用',
    [ResourceAvailabilityStatus.RESERVED]: '已预订',
    [ResourceAvailabilityStatus.IN_USE]: '使用中',
    [ResourceAvailabilityStatus.UNAVAILABLE]: '不可用',
    [ResourceAvailabilityStatus.FAILED]: '故障',
  };
  return labels[status] || status;
};

const getVersionStatusLabel = (status: ResourceVersionStatus) => {
  const labels = {
    [ResourceVersionStatus.DRAFT]: '草稿',
    [ResourceVersionStatus.STAGED]: '已暂存',
    [ResourceVersionStatus.CANARY]: '金丝雀发布',
    [ResourceVersionStatus.ACTIVE]: '活跃版本',
    [ResourceVersionStatus.DEPRECATED]: '已废弃',
    [ResourceVersionStatus.ROLLED_BACK]: '已回滚',
  };
  return labels[status] || status;
};

const getStatusTypeLabel = (type: string) => {
  const labels = {
    LIFECYCLE: '生命周期',
    AVAILABILITY: '可用性',
    VERSION: '版本',
  };
  return labels[type] || type;
};

const getStatusChangeColor = (type: string) => {
  const colors = {
    LIFECYCLE: 'blue',
    AVAILABILITY: 'green',
    VERSION: 'orange',
  };
  return colors[type] || 'default';
};

const formatTime = (time: string | Date) => {
  return new Date(time).toLocaleString('zh-CN');
};

// 状态更新函数
const updateLifecycleStatus = (status: ResourceLifecycleStatus) => {
  pendingStatusChange.value = { type: 'lifecycle', status };
  reasonModalVisible.value = true;
};

const updateAvailabilityStatus = (status: ResourceAvailabilityStatus) => {
  pendingStatusChange.value = { type: 'availability', status };
  reasonModalVisible.value = true;
};

const updateVersionStatus = (status: ResourceVersionStatus) => {
  pendingStatusChange.value = { type: 'version', status };
  reasonModalVisible.value = true;
};

const confirmStatusChange = async () => {
  if (!pendingStatusChange.value || !statusChangeReason.value.trim()) {
    message.error('请输入状态变更原因');
    return;
  }

  try {
    const { type, status } = pendingStatusChange.value;
    const reason = statusChangeReason.value;

    switch (type) {
      case 'lifecycle':
        lifecycleLoading.value = true;
        await updateResourceLifecycleStatus(
          props.resourceId,
          status as ResourceLifecycleStatus,
          reason,
        );
        resourceStatus.lifecycle = status as ResourceLifecycleStatus;
        break;
      case 'availability':
        availabilityLoading.value = true;
        await updateResourceAvailabilityStatus(
          props.resourceId,
          status as ResourceAvailabilityStatus,
          reason,
        );
        resourceStatus.availability = status as ResourceAvailabilityStatus;
        break;
      case 'version':
        versionLoading.value = true;
        await updateResourceVersionStatus(
          props.resourceId,
          status as ResourceVersionStatus,
          reason,
        );
        resourceStatus.version = status as ResourceVersionStatus;
        break;
    }

    resourceStatus.lastUpdated = new Date();
    message.success('状态更新成功');
    reasonModalVisible.value = false;
    statusChangeReason.value = '';
    pendingStatusChange.value = null;

    // 刷新状态历史
    await loadStatusHistory();
  } catch (error) {
    message.error('状态更新失败');
    console.error('状态更新失败:', error);
  } finally {
    lifecycleLoading.value = false;
    availabilityLoading.value = false;
    versionLoading.value = false;
  }
};

const cancelStatusChange = () => {
  reasonModalVisible.value = false;
  statusChangeReason.value = '';
  pendingStatusChange.value = null;

  // 恢复原状态
  loadResourceStatus();
};

// 数据加载函数
const loadResourceStatus = async () => {
  try {
    const response = await getResourceStatus(props.resourceId);
    if (response.code === 0) {
      Object.assign(resourceStatus, response.data);
    }
  } catch (error) {
    console.error('加载资源状态失败:', error);
  }
};

const loadStatusHistory = async () => {
  try {
    const response = await getResourceStatusHistory(props.resourceId);
    if (response.code === 0) {
      statusHistory.value = response.data;
    }
  } catch (error) {
    console.error('加载状态历史失败:', error);
  }
};

// 生命周期
onMounted(() => {
  loadResourceStatus();
  loadStatusHistory();
});
</script>

<style lang="less" scoped>
.resource-status-manager {
  .status-cards {
    .status-content {
      .status-info {
        margin-top: 8px;
        color: #666;
      }
    }
  }

  .status-change-item {
    .status-change-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 4px;

      .old-status {
        color: #666;
        text-decoration: line-through;
      }

      .new-status {
        font-weight: bold;
        color: #1890ff;
      }
    }

    .status-change-details {
      .reason {
        margin: 0;
        color: #333;
      }

      .meta {
        margin: 4px 0 0 0;
        color: #666;
        font-size: 12px;
      }
    }
  }
}
</style>
